<?php

namespace App\Exceptions;

use App\Http\Utils\Response;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use App\Exceptions\Exceptions\ValidationException as Validation;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception $e
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $e)
    {
        if ($request->wantsJson() || $request->ajax() || (env('APP_DEBUG') == false)) {
            $code = $e->getCode();
            $message = $e->getMessage();
            if ($e instanceof Validation) {
                $response = new Response(null, $message, 422);
            } else {
                if (substr($code, 0, 1) == 4 || substr($code, 0, 1) == 2) {// 4/2开头的错误抛给用户
                    $response = new Response(null, $message, $code);
                } else {
                    $response = new Response(null, '未知错误', 500);
                }
            }
            $response->header('P3P', 'CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
            $response->header('Cache-Control', "no-store");
            $response->header('Access-Control-Allow-Origin', "*");
            $response->header(
                'Access-Control-Allow-Headers',
                'Origin, Content-Type, Cookie, Content-Length, Authorization, Accept, X-Requested-With, Token'
            );
            $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
            return $response;
        } else {
            return parent::render($request, $e);
        }
    }
}
